import javafx.concurrent.Worker;

import java.util.concurrent.Semaphore;

/**
 * 信号量测试
 * 资源分配问题
 * Created by brss on 2018/3/25.
 */
public class SemaphoreTest {
    public static void main(String[] args) {
//        有8个人干活，但是只有5台机器的分配问题。
        int N = 8; //工人数
        Semaphore semaphore = new Semaphore(5);//机器数
        for (int i = 0 ; i < N ; i++ ){
            new Worker(i,semaphore).start();
        }
    }

    static class Worker extends Thread{

        private int num;

        private Semaphore semaphore;

        public Worker(int num , Semaphore semaphore){
            this.num = num;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try{
                semaphore.acquire();
                System.out.println("工人"+this.num+"占用了一个机器在生产。。。");
                Thread.sleep(2000);
                System.out.println("工人"+this.num+"释放机器");
                semaphore.release();

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }



}
